package agg

import (
	"gitee.com/bigmouth/quick-mock/src/domain/entity"
	"time"
)

// Namespace 命名空间聚合
type Namespace struct {
	namespace         entity.Namespace
	mockApiCollection []entity.MockApi
	disableTime       time.Time
}

func NewNamespace(namespace string, lifeTime int64) *Namespace {
	return &Namespace{
		namespace:         entity.NewNamespace(namespace),
		mockApiCollection: make([]entity.MockApi, 0),
		disableTime:       time.Now().Add(time.Duration(lifeTime * int64(time.Millisecond))),
	}
}

func (n *Namespace) GetMockApiList() []entity.MockApi {
	return n.mockApiCollection
}

func (n *Namespace) GetDisableTimeStr() string {
	return n.disableTime.Format("2006-01-02 15:04:05")
}

func (n *Namespace) AddMockApi(api entity.MockApi) {
	n.mockApiCollection = append(n.mockApiCollection, api)
}

func (n *Namespace) FindMockApi(path, method string, header, queryParam map[string]string, bodyJson map[string]interface{}) (entity.MockApi, bool, error) {
	for _, api := range n.mockApiCollection {
		// path
		isMatchPath, err := api.IsMatchPath(path)
		if err != nil {
			return entity.MockApi{}, false, err
		}
		if !isMatchPath {
			continue
		}

		// method
		isMatchMethod, err := api.IsMatchMethod(method)
		if err != nil {
			return entity.MockApi{}, false, err
		}
		if !isMatchMethod {
			continue
		}

		// header
		isMatchHeader := api.IsMatchHeader(header)
		if !isMatchHeader {
			continue
		}

		// query param
		isMatchQueryParam := api.IsMatchQueryParam(queryParam)
		if !isMatchQueryParam {
			continue
		}

		// body json
		isMatchBodyJson, err := api.IsMatchBodyJsonPattern(bodyJson)
		if err != nil {
			return entity.MockApi{}, false, err
		}
		if !isMatchBodyJson {
			continue
		}
		// 通过了
		return api, true, nil
	}
	return entity.MockApi{}, false, nil
}

func (n *Namespace) IsLive() bool {
	return n.disableTime.After(time.Now())
}
